<?php
namespace addons\service\library;

use app\api\model\service\ProjectConfigure;

class Map
{
    protected $reqUrl = "https://restapi.amap.com/v3/direction/driving?";
    protected $locationUrl = "https://restapi.amap.com/v3/geocode/regeo?output=JSON&location=";
    /**
     * 计算两地距离
     * @param $param
     * @return false|float
     */
    public static function countDistance($param)
    {
        $config = ProjectConfigure::where('state',1)->find();
        $params = http_build_query(['key'=>$config['gaodekey'],'origin'=>implode(',',$param['user']),'destination'=>implode(',',$param['skill'])]);
        $url = (new Map())->reqUrl.$params;
        $res = self::getUrl($url);
        $distance = ceil($res['route']['paths'][0]['distance']/1000);
        return $distance;
    }

    /**
     * 根据经纬度获取详细地址
     * @param $lng
     * @param $lat
     * @return false|mixed
     */
    public static function getLocation($lng,$lat)
    {
        $config = ProjectConfigure::getProjectConfig();
        $key = $config['gaodekey'];
        $location = $lng . "," . $lat;
        $url = (new Map())->locationUrl."{$location}&key={$key}&radius=1000&extensions=all";
        $re = self::getUrl($url);
        if($re['status'] != 1){
            return false;
        }
        return $re;
    }


    public static function getUrl($url) {
        //初始化
        $ch = curl_init();
        //设置选项，包括URL
        curl_setopt($ch, CURLOPT_URL,$url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_HEADER, 0);
        //执行并获取HTML文档内容
        $output = curl_exec($ch);
        //释放curl句柄
        curl_close($ch);
        //打印获得的数据
        return json_decode($output,true);
    }
}
